package com.yupi.springbootinit.manager;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.datasource.DataSource;
import com.yupi.springbootinit.datasource.DataSourceRegister;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.search.SearchRequest;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.model.entity.Video;
import com.yupi.springbootinit.model.enums.SearchTypeEnum;
import com.yupi.springbootinit.model.vo.PostVO;
import com.yupi.springbootinit.model.vo.SearchVO;
import com.yupi.springbootinit.model.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Component
public class SearchFacade {

    @Resource
    private DataSource<Picture> pictureDataSource;

    @Resource
    private DataSource<PostVO> postVODataSource;

    @Resource
    private DataSource<UserVO> userVODataSource;

    @Resource
    private DataSource<Video> videoDataSource;

    @Resource
    private DataSourceRegister dataSourceRegister;

    public SearchVO searchAll(SearchRequest searchRequest, HttpServletRequest request) {
        String type = searchRequest.getType();
        String searchText = searchRequest.getSearchText();
        if(StringUtils.isBlank(searchText)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"搜索内容为空");
        }

        SearchTypeEnum enumByValue = SearchTypeEnum.getEnumByValue(type);
        if (enumByValue != null) {
            SearchVO searchVO = new SearchVO();
            DataSource<?> dataSource = dataSourceRegister.getDataSource(type);
            Page<?> pageList = dataSource.doSearch(searchText, searchRequest.getCurrent(), 8);
            searchVO.setDataList(pageList.getRecords());
            return searchVO;
        } else {
            // 获取图片列表
            Page<Picture> picturePageList = pictureDataSource.doSearch(searchText, 1, 8);

            // 获取帖子列表
            Page<PostVO> postVOPageList = postVODataSource.doSearch(searchText, 1, 8);

            // 获取用户列表
            Page<UserVO> userVOPageList = userVODataSource.doSearch(searchText, 1, 8);

            Page<Video> videoPageList = videoDataSource.doSearch(searchText,1,8);
            // 将其封装成一个 SearchVO类，用于返回数据给前端接受
            SearchVO searchVO = new SearchVO();
            searchVO.setUserList(userVOPageList.getRecords());
            searchVO.setPostList(postVOPageList.getRecords());
            searchVO.setPictureList(picturePageList.getRecords());
            searchVO.setVideoList(videoPageList.getRecords());
            return searchVO;
        }

    }
}
